package com.uu.safeguard.utils;

import net.sf.json.JSONObject;
import redis.clients.jedis.Jedis;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SocketUtil {
    //结束充电
    public static void end_charge(String sn,String platform_sn) {
        long timestamp =  System.currentTimeMillis();
        Jedis jedis = JedisUtil.getJedis();

        if(jedis.hexists(sn,"state")  ){


            if(jedis.hget(sn,"state")  .equals("2") ) {


                if (jedis.exists(sn)) {


                    Map<String, String> result = jedis.hgetAll(sn);

                    System.out.println("result " + result);

                    if (!result.containsKey("charge_log_id") || !result.containsKey("money_total") || !result.containsKey("degree")) {

                        System.out.println("结束充电有问题");
                    }


                    String member_sn = result.get("member_sn");
                    String safe_money = result.get("safe_money");
                    String charge_log_id = result.get("charge_log_id");
//                String remain_millisecond = result.get("remain_millisecond").toString();
//
//
//
//                BigDecimal bd = new BigDecimal(remain_millisecond);
//
//                long remain_millisecond2 =bd.longValue() ;
                    //

                    long remain_millisecond=0;

                    String degreeS = result.get("degree").toString();
                    DecimalFormat format = new DecimalFormat("0.0000");
                    String adegree = format.format(new BigDecimal(degreeS));
                    Double degree = Double.valueOf(adegree);
                    //
                    int power_total = Integer.valueOf( result.get("power_total"));
                    int power_count =  Integer.valueOf( result.get("power_count"));

                    String money_totalS = result.get("money_total").toString();
                    String amoney_total = format.format(new BigDecimal(money_totalS));
                    Double money_total = Double.valueOf(amoney_total);

                    String actual_moneyS = result.get("actual_money").toString();
                    String aactual_money = format.format(new BigDecimal(actual_moneyS));
                    Double actual_money = Double.valueOf(aactual_money);


                    String discount_moneyS = result.get("discount_money").toString();
                    String adiscount_money = format.format(new BigDecimal(discount_moneyS));
                    Double discount_money = Double.valueOf(adiscount_money);


                    int end_reason = Integer.valueOf(result.get("end_reason"));

                    String moneyTotalTemp_startingPriceS = result.get("moneyTotalTemp_startingPrice").toString();
                    String amoneyTotalTemp_startingPrice = format.format(new BigDecimal(moneyTotalTemp_startingPriceS));
                    Double moneyTotalTemp_startingPrice = Double.valueOf(amoneyTotalTemp_startingPrice);


                    DbUtil db = new DbUtil();
                    String sql = "end_charge_proc(?,?,?,?,?,?,?,?,?,?,?,?,?)";
                    List parameter = new ArrayList<Object>() {{
                        add(sn);
                        add(charge_log_id);
                        add(timestamp);
                        add(end_reason);
                        add(power_total);
                        add(power_count);
                        add(member_sn);
                        add(remain_millisecond);
                        add(money_total);
                        add(actual_money);
                        add(discount_money);
                        add(degree);
                        add(moneyTotalTemp_startingPrice);
                    }};

                    jedis.del(sn);
                    //System.out.println("sql:"+sql );

                    //System.out.println("parameter:"+parameter );

                    int aaa = (int) db.executeCall(sql, parameter, 1);

                    if (aaa == 1) {
                        //转移功率
                        tranPower(sn);
                        //发送关闭模板消息
                        Map platform = db.table("platform").where(new ArrayList() {{
                            add(new ArrayList() {{
                                add("sn");
                                add("=");
                                add(platform_sn);
                            }});
                        }}).find("member_url");
                        long nowTime = System.currentTimeMillis();
                        String url = platform.get("member_url").toString() + "/internalApi/sendEndSocketTmplMsg";
                        Map contentMap = new HashMap<>();
                        contentMap.put("charge_log_id",charge_log_id);
                        contentMap.put("nonce_str",nowTime + "sssz");
                        contentMap.put("timestamp",nowTime + "");
                        contentMap.put("sign", CommonUtil.makeSign(contentMap,"sdvDDnoDnalDdDkvSAS54aFSFSDd561a6DF5S1a6sd156sa1d","MD5"));
                        String content = JSONObject.fromObject(contentMap).toString();
                        String post = HttpUtil.post(url, new HashMap<>(), content);
                    }

                }

            }
        }
        JedisUtil.close(jedis);
    }


    //功率转移
    public static void tranPower(String sn) {
        Jedis jedis1 = JedisUtil.getJedis();
        try {
            DbUtil db = new DbUtil();

            jedis1.select(1);
            List<String> listA = jedis1.lrange(sn, 0, -1);
            boolean hasKey = jedis1.exists(sn);

            if (listA.size() != 0) {

                if (hasKey) {

                    int jsize = (int) listA.size() / 100;

                    for (int j = 0; j < jsize + 2; j++) {

                        if (jsize > 0 && j == 0) {
                            j = 1;
                        }
                        int k = (j - 1) * 100;
                        if (jsize == 0 && j == 0) {
                            k = 0;
                        }

                        int l = j * 100 - 1;

                        if (j == jsize + 1) {
                            l = -1;
                        }

                        List<String> list = jedis1.lrange(sn, k, l);
                        for (int i = 0; i < list.size(); i++) {
                            List insert = new ArrayList();
                            JSONObject jsonObj = JSONObject.fromObject(list.get(i));
                            //logger.info("jsonObj:"+jsonObj);

                            String member_sn1 = jsonObj.getString("member_sn");
                            String station_sn1 = jsonObj.getString("station_sn");
                            String charge_log_id1 = jsonObj.getString("charge_log_id");
                            String socket_number1 = jsonObj.getString("socket_number");
                            String power_time1 = jsonObj.getString("power_time");
                            String power_value1 = jsonObj.getString("power_value");
                            //插入多条

                            HashMap HashMap = new HashMap() {
                                {
                                    put("member_sn", member_sn1);
                                    put("station_sn", station_sn1);
                                    put("charge_log_id", charge_log_id1);
                                    put("socket_number", socket_number1);
                                    put("power_time", power_time1);
                                    put("power_value", power_value1);
                                    put("socket_sn", sn);
                                }
                            };
                            //logger.info("HashMap:" + HashMap);
                            insert.add(HashMap);
                            db.table("power_value_log").insertAll(insert);
                        }

                        //打印sql语句
                        //logger.info("sql语句："+db.getLastSql());
                        if (l == -1) {
                            break;
                        }
                    }
                    jedis1.del(sn);
                }

            }

        } catch (Exception e) {
            System.out.println("tranPower_ERROR" + e.toString());
        }
        finally {
            JedisUtil.close(jedis1);
        }
    }
}
